<script setup>
import { ref, watch } from 'vue';
import axios from 'axios';
import PianoAudioGenerator from './components/PianoAudioGenerator.vue';

const activeTab = ref('basic'); // 'basic' 或 'piano'

const frequency = ref('');
const audioUrl = ref('');
const currentAudioUrl = ref('');
const filePath = ref('');
const showFilePath = ref(false);
const loading = ref(false);
const error = ref('');
const bgmMode = ref(false);

// 监听音频URL变化，释放旧资源
watch(currentAudioUrl, (newVal, oldVal) => {
  if (oldVal) {
    URL.revokeObjectURL(oldVal);
  }
});

async function generateAudio() {
  // 重置状态
  audioUrl.value = '';
  error.value = '';
  
  // 验证输入
  const freqValue = parseFloat(frequency.value);
  if (isNaN(freqValue) || freqValue <= 0) {
    error.value = '请输入有效的频率值（大于0的数字）';
    return;
  }
  
  try {
    loading.value = true;
    // 发送请求到后端
    const response = await axios.post('http://localhost:3001/generate-audio', {
      frequency: freqValue
    });
    
    // 获取生成的音频URL和文件名
    audioUrl.value = response.data.audioUrl;
    filePath.value = response.data.filePath;
    showFilePath.value = true;
    
    // 自动隐藏文件路径提示
    setTimeout(() => {
      const toast = document.querySelector('.path-toast');
      if (toast) toast.style.opacity = '0';
      setTimeout(() => showFilePath.value = false, 500);
    }, 4000);
  } catch (err) {
    console.error('生成音频失败:', err);
    error.value = err.response?.data?.error || '生成音频失败，请稍后重试';
  } finally {
    loading.value = false;
  }
}

const downloadAudio = () => {
  if (!audioUrl.value) return;
  const link = document.createElement('a');
  link.href = audioUrl.value;
  // 从URL提取文件名
  const urlParts = audioUrl.value.split('/');
  const fileName = urlParts[urlParts.length - 1];
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

const playPianoNote = async (frequency) => {
  try {
    const isBGM = bgmMode.value;
    console.log(`发送钢琴演奏请求:频率=${frequency}, 模式=${isBGM ? 'BGM' : '普通'}`);
    
    // 清除上一个音频
    if (currentAudioUrl.value) {
      URL.revokeObjectURL(currentAudioUrl.value);
      currentAudioUrl.value = '';
    }

    const response = await axios.post('/api/piano/play', {
      frequency,
      isBGM
    }, isBGM ? { responseType: 'blob' } : {});

    if (isBGM) {
      // BGM模式：处理二进制音频数据
      const audioBlob = new Blob([response.data], { type: 'audio/wav' });
      currentAudioUrl.value = URL.createObjectURL(audioBlob);
    } else {
      // 普通模式：使用音频URL
      currentAudioUrl.value = `http://localhost:3001${response.data.url}`;
    }
  } catch (error) {
    console.error('播放钢琴音符失败:', error.response?.data || error.message);
    error.value = error.response?.data?.error || '播放失败，请重试';
  }
};
</script>

<template>
  <div class="audio-generator">
    <h1>音频生成工具</h1>
    <div class="tabs">
      <button 
        class="tab-btn" 
        :class="{ active: activeTab === 'basic' }"
        @click="activeTab = 'basic'"
      >
        基础音频生成
      </button>
      <button 
        class="tab-btn" 
        :class="{ active: activeTab === 'piano' }"
        @click="activeTab = 'piano'"
      >
钢琴演奏
      </button>
      <button 
        class="tab-btn"
        :class="{ active: activeTab === 'tone' }"
        @click="activeTab = 'tone'"
      >
        钢琴音色生成
      </button>
    </div>
    
    <!-- 基础音频生成标签页 -->
    <div v-if="activeTab === 'basic'" class="tab-content">
      <div class="input-section">
        <label for="frequency">输入频率 (Hz):</label>
        <input 
          id="frequency" 
          type="number" 
          v-model="frequency" 
          placeholder="例如: 440"
          min="0.1"
          step="0.1"
          :disabled="loading"
        />
        <button @click="generateAudio" :disabled="loading">
          {{ loading ? '生成中...' : '生成音频' }}
        </button>
      </div>
      
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
      
      <div v-if="audioUrl" class="audio-section">
        <div v-if="showFilePath" class="path-toast">
          保存路径: {{ filePath }}
        </div>
        <audio :src="audioUrl" controls> 
          您的浏览器不支持音频播放
        </audio>
        <button @click="downloadAudio" class="download-btn">
          下载WAV文件
        </button>
      </div>
    </div>

    <!-- 钢琴演奏标签页 -->
    <div v-else-if="activeTab === 'piano'" class="tab-content piano-tab-content">
      <div class="piano-layout">
        <div class="keyboard-section">
          <div class="mode-toggle">
            <label class="switch">
              <input type="checkbox" v-model="bgmMode">
              <span class="slider round"></span>
            </label>
            <span class="mode-label">{{ bgmMode ? 'BGM模式' : '普通模式' }}</span>
          </div>
          <div class="piano-keyboard">
            <div class="piano-octave">
              <!-- 白键 -->
              <button class="piano-key white" @click="playPianoNote(261.63)">C4</button>
              <button class="piano-key white" @click="playPianoNote(293.66)">D4</button>
              <button class="piano-key white" @click="playPianoNote(329.63)">E4</button>
              <button class="piano-key white" @click="playPianoNote(349.23)">F4</button>
              <button class="piano-key white" @click="playPianoNote(392.00)">G4</button>
              <button class="piano-key white" @click="playPianoNote(440.00)">A4</button>
              <button class="piano-key white" @click="playPianoNote(493.88)">B4</button>
              <button class="piano-key white" @click="playPianoNote(523.25)">C5</button>
              
              <!-- 黑键 -->
              <button class="piano-key black" @click="playPianoNote(277.18)">C#4</button>
              <button class="piano-key black" @click="playPianoNote(311.13)">D#4</button>
              <button class="piano-key black" @click="playPianoNote(369.99)">F#4</button>
              <button class="piano-key black" @click="playPianoNote(415.30)">G#4</button>
              <button class="piano-key black" @click="playPianoNote(466.16)">A#4</button>
            </div>
          </div>
          
          <div class="audio-player" v-if="currentAudioUrl">
            <audio :src="currentAudioUrl" autoplay :controls="!bgmMode">
              您的浏览器不支持音频播放
            </audio>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 钢琴音色生成标签页 -->
    <div v-else-if="activeTab === 'tone'" class="tab-content">
      <h3>钢琴音色生成</h3>
      <div class="tone-generation-section">
        <PianoAudioGenerator />
      </div>
    </div>
  </div>
</template>

<style scoped>
.audio-generator {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #ccc;
}

.tab-btn {
  padding: 10px 20px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-bottom: none;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: all 0.3s;
  border-radius: 4px 4px 0 0;
  margin-right: 5px;
}

.tab-btn.active {
  background-color: white;
  border-bottom: 2px solid #42b883;
  color: #333;
  font-weight: bold;
}

.tab-btn:hover:not(.active) {
  background-color: #e6e6e6;
  color: #444;
}

.tab-content {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}

/* 基础音频生成样式 */
.input-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.input-section label {
  font-weight: bold;
  color: #555;
  min-width: 120px;
}

.input-section input {
  flex: 1;
  min-width: 200px;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #3aa873;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.error-message {
  color: #e74c3c;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fee;
  border-radius: 4px;
}

.audio-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

audio {
  width: 100%;
  margin: 15px 0;
}

.path-toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.8);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  transition: opacity 0.5s ease-out;
  z-index: 1000;
  opacity: 1;
}

.download-btn {
  margin-top: 10px;
  background-color: #3498db;
}

.download-btn:hover {
  background-color: #2980b9;
}

/* 钢琴演奏样式 */
.piano-tab-content {
  min-height: 400px;
}

.piano-layout {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.keyboard-section {
  flex: 1;
  overflow-x: auto;
  padding-bottom: 10px;
}

.mode-toggle {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #42b883;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.mode-label {
  font-size: 14px;
  color: #666;
}

.settings-subwindow {
  width: 250px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  height: fit-content;
}

.settings-subwindow h3 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/* 钢琴键盘样式 */
.piano-keyboard {
  margin-bottom: 20px;
}

.piano-octave {
  position: relative;
  height: 520px;
  display: grid;
  grid-template-columns: repeat(5, 100px);
  grid-template-rows: repeat(2, 240px);
  gap: 3px;
  width: 512px;
  margin: 0 auto;
  padding: 5px;
}

.piano-key {
  position: relative;
  border: none;
  cursor: pointer;
  transition: all 0.1s ease;
}

.piano-key.white {
  width: 100px;
  height: 240px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 0 0 5px 5px;
  z-index: 1;
  position: relative;
  margin: 0;
}

.piano-key.white:active {
  background: #f0f0f0;
  transform: translateY(2px);
}

.piano-key.black {
  display: none;
  position: absolute;
  width: 60px;
  height: 140px;
  background: #333;
  z-index: 2;
  right: -30px;
  top: 0;
}

.piano-key.black:active {
  background: #555;
  transform: translateY(1px);
}

.audio-player {
  margin-top: 20px;
}
</style>
